<?php

namespace App\Http\Controllers;

use App\FreeCar;
use Illuminate\Http\Request;
use App\Http\Resources\FreeCarCollection;
use App\Http\Resources\FreeCarResource;
use Illuminate\Http\Response;

class FreeCarController extends Controller
{
    // 定义需要查询的字段
    private static $s = [
        'id',
        'licensePlate',
        'constructionUnit',
        'freeTimeStart',
        'freeTimeEnd',
        'freeSection',
        'vehicleType',
        'theValidityPeriodOfTheAnnualInspectionOfTheVehicle',
        'validityPeriodOfVehicleInsurance',
        'updatedDate',
        'photo',
        'remark'
    ];

    /**
     * Display a listing of the resource.
     *
     * @return App\Http\Resources\FreeCarCollection
     */
    public function index(Request $request)
    {
        // 获取每页显示的条数
        $perPage = $request->perPage ?? $request->per_page ?? 88;
        // 获取 日期
        $dieLine = now()->format('Y-m-d');
        // dd($dieLine);
        // 查询所有数据并分页
        $data = FreeCar::query()->select(self::$s)
            ->whereDate('freeTimeEnd', '>', $dieLine)
            ->latest('updatedDate')
            ->paginate($perPage);
        // 返回数据
        return FreeCarResource::collection($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request
     * @return FreeCarResource
     */
    public function store(Request $request)
    {
        // 验证请求
        $freeCar = new FreeCar();
        // 获取请求中的数据
        $formData = $request->all(self::$s);
        // 将数据映射到freeCar对象中
        collect($formData)->forget('id')->map(function ($v, $k) use ($freeCar) {
            $freeCar->$k = $v;
        });
        // 保存数据
        $res = $freeCar->save();
        // 返回保存结果
        if ($res) {
            return new FreeCarResource($freeCar);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param FreeCar $freeCar
     * @return FreeCarResource
     */
    public function show(FreeCar $freeCar)
    {
        // 查询指定id的数据
        return new FreeCarResource(FreeCar::query()->select(self::$s)->find($freeCar));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request
     * @param FreeCar $freeCar
     * @return FreeCar|void
     */
    public function update(Request $request, FreeCar $freeCar)
    {
        // 更新数据
        // 获取请求中的数据
        $formData = $request->all(self::$s);
        // 将数据映射到freeCar对象中
        collect($formData)->forget('id')->map(function ($v, $k) use ($freeCar) {
            $freeCar->$k = $v;
        });
        // 保存数据
        $res = $freeCar->update();
        if ($res) {
            // return $freeCar;
            return new FreeCarResource($freeCar);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param FreeCar $freeCar
     * @return int
     */
    public function destroy(FreeCar $freeCar): int
    {
        // 删除数据
        return $freeCar->delete();
    }
}
